package com.xique.door.bean.validation;

import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.request.user.UserAddCardRequest;
import com.xique.door.bean.request.user.UserAddHouseRequest;
import com.xique.door.bean.request.user.UserAddRequest;
import com.xique.door.bean.request.user.UserEditRequest;
import com.xique.door.biz.service.impl.BuildHouseBizService;
import com.xique.door.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @Auther: caogq @Date: 2021/7/7 11:32 @Description:
 */
@Component
public class UserValidation {
    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IDCardService dCardService;

    @Autowired
    private BuildHouseBizService buildHouseBizService;

    @Autowired
    private IBuildHouseService houseService;

    @Autowired
    private IBuildHouseUserService houseUserService;

    @Autowired
    private IDCardHouseService dCardHouseService;

    /**
     * 判断是否可以删除用户 1、是否有访客； 2、是否有卡片；
     *
     * @param user
     * @return
     */
    public AjaxResult deleteUser(User user) {
        Visitor visitor = new Visitor();
        visitor.setUserId(user.getId());
        List<Visitor> visitors = visitorService.selectVisitorList(visitor);
        if (!visitors.isEmpty()) {
            return AjaxResult.error("请先清除用户的访客，再删除用户！");
        }
        DCard dCard = new DCard();
        dCard.setUserId(user.getId());
        List<DCard> dCardList = dCardService.selectDCardList(dCard);
        if (!dCardList.isEmpty()) {
            return AjaxResult.error("请先清除用户的卡片，再删除用户！");
        }
        return AjaxResult.success();
    }

    public AjaxResult addUserValidate(UserAddRequest request) {
        if (StringUtils.isEmpty(request.getUserName())) {
            return AjaxResult.error("用户名称不能为空");
        }
        // 校验手机号重复
        if (!StringUtils.isEmpty(request.getPhone())) {
            User search = new User(request.getParkId(), request.getPhone());
            search.setDelFlag(0);
            List<User> users = userService.selectUserList(search);
            if (!users.isEmpty()) {
                return AjaxResult.error("手机号已存在！");
            }
        }
        List<UserAddHouseRequest> houses = request.getHouses();
        if (!CollectionUtils.isEmpty(houses)) {
            for (UserAddHouseRequest house : houses) {
                if (house.getHouseId() != null) {
                    Boolean ownerExistFlag = buildHouseBizService.judgeIsHouseOwnerExist(house.getHouseId());
                    if (("0").equals(house.getIdentityType()) && ownerExistFlag == true) {
                        return AjaxResult.error("房屋已存在业主，请确认身份类型后再提交！");
                    }
                    BuildHouseV1 houseV1 = houseService.getById(house.getHouseId());
                    if (!StringUtils.isNull(houseV1) && !StringUtils.isNull(houseV1.getMaxInNumber())) {
                        int count = houseUserService.checkHouseUserCount(house.getHouseId());
                        if (count >= houseV1.getMaxInNumber()) {
                            return AjaxResult.error(houseV1.getHouseName()+"已超出该房屋最大可入住数量");
                        }
                    }
                }
            }
            if (houses.get(0).getCards() != null) {
                List<UserAddCardRequest> cards = houses.get(0).getCards();
                // 判断卡号在该项目中是否重复
                for (UserAddCardRequest card : cards) {
                    if (StringUtils.isEmpty(card.getCardSn())) {
                        continue;
                    }
                    DCard search = new DCard();
                    search.setParkId(SecurityUtils.getParkId());
                    search.setCardSn(card.getCardSn());
                    List<DCard> dCards = dCardService.selectCardList(search);
                    if (!dCards.isEmpty()) {
                        DCardHouse dCardHouse = new DCardHouse();
                        dCardHouse.setCardId(dCards.get(0).getId());
                        List<DCardHouse> dCardHouseList = dCardHouseService.selectDCardHouseList(dCardHouse);
                        if (!dCardHouseList.isEmpty()) {
                            return AjaxResult.error("卡号:" + dCards.get(0).getCardSn() + "已绑定房屋");
                        }

                    }
                }
            }
        }

        return AjaxResult.success();
    }

    public AjaxResult updateUserValidate(UserEditRequest request) {
        if (StringUtils.isEmpty(request.getUserName())) {
            return AjaxResult.error("用户名称不能为空");
        }
        if (StringUtils.isNotEmpty(request.getPhone())) {
            // 校验手机号重复
            User orignUser = userService.selectUserById(request.getId());
            User search = new User(orignUser.getParkId(), request.getPhone());
            search.setDelFlag(0);
            List<User> users = userService.selectUserList(search);
            String orignPhone = StringUtils.isNull(orignUser.getPhone()) ? "" : orignUser.getPhone();
            String newPhone = request.getPhone();
            // 判断逻辑：用户修改了手机号，并且修改的手机号已经存在对应的用户
            if (!users.isEmpty() && !orignPhone.equals(newPhone)) {
                return AjaxResult.error("手机号已存在！");
            }
//      if (StringUtils.isNull(orignUser.getBaseUserId())) {
//        // 根据手机号维护c_base_user表
//        BaseUser baseUser1 = baseUserService.selectBaseUserByLoginName(request.getPhone());
//        if (StringUtils.isNull(baseUser1)) {
//          BaseUser baseUser = new BaseUser();
//          baseUser.setCellphone(request.getPhone());
//          baseUser.setUserName(request.getUserName());
//          baseUser.setStatus("1");
//          baseUser.setDelFlag("0");
//          baseUser.setRemark("门禁用户修改，维护数据");
//          baseUser.setCreateTime(new Date());
//          baseUser.setCreateUser(SecurityUtils.getUserId());
//          baseUser.setRemark("修改保存门禁用户添加");
//          baseUserService.insertBaseUser(baseUser);
//          request.setBaseUserId(baseUser.getId());
//        } else {
//          request.setBaseUserId(baseUser1.getId());
//        }
//      } else {
//        BaseUser baseUser = new BaseUser();
//        baseUser.setId(orignUser.getBaseUserId());
//        baseUser.setCellphone(request.getPhone());
//        if (StringUtils.isNotEmpty(request.getFaceKey())) {
//          baseUser.setFaceKey(request.getFaceKey());
//          baseUser.setFaceUrl(request.getFaceUrl());
//        }
//        baseUserService.updateBaseUser(baseUser);
//        request.setBaseUserId(orignUser.getBaseUserId());
//      }
      /*
      // 根据手机号维护c_base_user表
      BaseUser baseUser1 = baseUserService.selectBaseUserByLoginName(orignPhone);
      if (baseUser1 == null) {
        BaseUser baseUser = new BaseUser();
        baseUser.setCellphone(request.getPhone());
        baseUser.setUserName(request.getUserName());
        baseUser.setStatus("1");
        baseUser.setDelFlag("0");
        baseUser.setRemark("门禁用户修改，维护数据");
        baseUser.setCreateTime(new Date());
        baseUser.setCreateUser(SecurityUtils.getUserId());
        baseUserService.insertBaseUser(baseUser);
        request.setBaseUserId(baseUser.getId());
      } else {
        BaseUser baseUser = new BaseUser();
        baseUser.setId(baseUser1.getId());
        baseUser.setCellphone(request.getPhone());
        if (StringUtils.isNotEmpty(request.getFaceKey())) {
          baseUser.setFaceKey(request.getFaceKey());
          baseUser.setFaceUrl(request.getFaceUrl());
        }
        baseUserService.updateBaseUser(baseUser);
        request.setBaseUserId(baseUser1.getId());
      }
       */
        }
        return AjaxResult.success();
    }

    /**
     * 验证用户信息是否修改，是否需要同步海康
     *
     * @param
     * @return
     */
    public Boolean validateUserUpdateNeedSync(User newUser) {
        User oldUser = userService.selectUserById(newUser.getId());
        if (!StringUtils.equals(oldUser.getFaceUrl(), newUser.getFaceUrlNew())) {
            return true;
        }
        return false;
    }
}
